// RTSPServerManager.cpp
// RTSP服务器管理器实现

#include "RTSPServerManager.hh"
#include "../service/Logger.hh"
#include "../service/RAIIHelpers.hh"
#include "T32H264LiveSource.hh"
#include "H264VideoServerMediaSubsession.hh"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <memory>
#include <mutex>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 使用新的日志系统（Logger.hh中已定义宏）

// 创建新的RTSP服务器管理器实例（使用默认配置）
RTSPServerManager* RTSPServerManager::createNew() {
    return new RTSPServerManager();
}

// 创建新的RTSP服务器管理器实例（使用自定义配置）
RTSPServerManager* RTSPServerManager::createNew(const RTSPConfig& config) {
    RTSPServerManager* manager = new RTSPServerManager();
    if (manager != NULL) {
        manager->fConfig = config;
    }
    return manager;
}

// 构造函数
RTSPServerManager::RTSPServerManager()
    : fServerThread(0),
      fScheduler(NULL),
      fEnv(NULL),
      fRTSPServer(NULL),
      fMediaSession(NULL),
      fEventLoopWatchVar(NULL),
      fVideoHandler(NULL),
      // fAudioHandler(NULL),  // 音频功能暂未实现
      fLiveSource(NULL),
      fVideoReplicator(NULL),
      fVideoSubsession(NULL),
      // [自定义] 获取默认配置
    fConfig(ConfigManager::getDefaultConfig()),
      fShouldStop(false),
      fServerRunning(false),
      fInitialized(false) {
    // 初始化互斥锁
    pthread_mutex_init(&fMutex, NULL);
    // [自定义] 日志输出
    LOG_INFO("RTSPServerManager created");
}

// 析构函数
RTSPServerManager::~RTSPServerManager() {
    cleanup();
    pthread_mutex_destroy(&fMutex);
    // [自定义] 日志输出
    LOG_INFO("RTSPServerManager destroyed");
}

// 初始化RTSP服务器（使用默认配置）
bool RTSPServerManager::initialize(int port) {
    // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
    
    if (fInitialized) {
        LOG_ERROR("RTSP server already initialized");
        return false;
    }
    
    // [自定义] 使用默认配置，但更新端口
    fConfig = ConfigManager::createConfigFrom(fConfig, port);
    // [自定义] 验证配置
    if (!ConfigManager::validateConfig(fConfig)) {
        LOG_ERROR("Invalid port: %d", port);
        return false;
    }
    
    fInitialized = true;
    LOG_INFO("RTSPServerManager initialized with port %d", port);
    
    return true;
}

// 初始化RTSP服务器（使用自定义配置）
bool RTSPServerManager::initialize(const RTSPConfig& config) {
    // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
    
    if (fInitialized) {
        LOG_ERROR("RTSP server already initialized");
        return false;
    }
    
    // [自定义] 验证配置
    if (!ConfigManager::validateConfig(config)) {
        LOG_ERROR("Invalid configuration provided");
        return false;
    }
    
    fConfig = config;
    fInitialized = true;
    LOG_INFO("RTSPServerManager initialized with custom config (port: %d)", config.port);
    
    return true;
}

// 启动RTSP服务器
bool RTSPServerManager::start() {
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        
        if (fServerRunning || fServerThread != 0) {
            LOG_ERROR("RTSP server already running");
            return false;
        }
        
        if (!fInitialized) {
            LOG_ERROR("RTSP server not initialized");
            return false;
        }
        
        fShouldStop = false;
    }
    
    // 创建服务器线程（直接传递this指针，不需要额外分配内存）
    if (pthread_create(&fServerThread, NULL, serverThreadFunc, this) != 0) {
        LOG_ERROR("Failed to create RTSP server thread");
        return false;
    }
    
    // 等待服务器初始化
    usleep(200000);
    
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        if (!fServerRunning) {
            LOG_ERROR("RTSP server failed to initialize");
            // 清理线程
            if (fServerThread != 0) {
                pthread_join(fServerThread, NULL);
                fServerThread = 0;
            }
            return false;
        }
    }
    
    LOG_INFO("RTSP server started on port %d", fConfig.port);
    return true;
}

// 停止RTSP服务器
void RTSPServerManager::stop() {
    LOG_INFO("Stopping RTSP server");
    
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        if (!fServerRunning) {
            LOG_WARNING("RTSP server is not running");
            return;
        }
        fShouldStop = true;
    }
    
    // 通知事件循环退出（需要在锁外执行，避免死锁）
    if (fEventLoopWatchVar != NULL) {
        *fEventLoopWatchVar = 1;
    }
    
    if (fServerThread != 0) {
        pthread_join(fServerThread, NULL);
        fServerThread = 0;
    }
    
    cleanup();
    
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        fServerRunning = false;
    }
    
    LOG_INFO("RTSP server stopped");
}

// 更新视频参数集
void RTSPServerManager::updateVideoParams(unsigned char* spsData, size_t spsSize,
                                          unsigned char* ppsData, size_t ppsSize) {
    // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
    
    if (fVideoHandler) {
        // [自定义] 更新视频参数集
        fVideoHandler->updateParameterSets(spsData, spsSize, ppsData, ppsSize);
        // 只在成功更新时记录日志（降低日志频率）
        static unsigned updateCount = 0;
        updateCount++;
        if (updateCount % 100 == 0) {
            LOG_INFO("Updated video parameter sets (count: %u)", updateCount);
        }
    } else {
        // Video handler 未初始化，这是正常情况（可能在初始化过程中）
        // 静默处理，不记录错误日志，避免日志污染
        // 当 Video handler 初始化后，SPS/PPS 会在下次检测到时更新
    }
}

// 通知有新视频帧可用
void RTSPServerManager::notifyNewFrameAvailable() {
    T32H264LiveSource* liveSource = nullptr;
    {
        ThreadSafeUtils::ScopedLock lock(fMutex);
        if (fVideoHandler) {
            fVideoHandler->notifyNewFrameAvailable();
        }
        liveSource = fLiveSource;
    }

    if (liveSource != nullptr) {
        liveSource->signalNewFrame();
    } else {
        LOG_DEBUG("Frame notification dropped: live source not ready");
    }
}

// isRunning() 和 getConfig() 已在头文件中内联实现，这里不需要重复定义

// 服务器线程函数
void* RTSPServerManager::serverThreadFunc(void* arg) {
    RTSPServerManager* manager = static_cast<RTSPServerManager*>(arg);
    if (manager) {
        manager->serverMainLoop();
    } else {
        LOG_ERROR("Invalid manager pointer in server thread");
    }
    return NULL;
}

// 服务器线程主循环
void RTSPServerManager::serverMainLoop() {
    LOG_INFO("RTSP server thread started");
    
    // 获取配置（在锁保护下）
    RTSPConfig config;
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        config = fConfig;
    }
    
    // ========== Live555库函数调用 ==========
    // [Live555] 创建任务调度器
    fScheduler = BasicTaskScheduler::createNew();
    if (fScheduler == nullptr) {
        LOG_ERROR("Failed to create task scheduler");
        return;
    }
    LOG_INFO("Task scheduler created");
 
    // [Live555] 创建使用环境
    fEnv = BasicUsageEnvironment::createNew(*fScheduler);
    if (fEnv == nullptr) {
        LOG_ERROR("Failed to create usage environment");
        delete fScheduler;
        fScheduler = nullptr;
        return;
    }
    LOG_INFO("Usage environment created");
    
    // [Live555] 创建带日志功能的RTSP服务器（使用配置中的端口）
    Port rtspPort(config.port);
    fRTSPServer = LoggingRTSPServer::createNew(*fEnv, rtspPort);
    if (fRTSPServer == NULL) {
        // [Live555] 获取错误消息
        const char* errorMsg = fEnv->getResultMsg();
        LOG_ERROR("Failed to create RTSP server on port %d: %s", config.port, errorMsg);
        
        // 检查是否是端口占用错误，提供更详细的错误信息
        if (errorMsg != NULL && strstr(errorMsg, "Address already in use") != NULL) {
            LOG_ERROR("Port %d is already in use. Please:");
            LOG_ERROR("  1. Stop any existing RTSP server instance");
            LOG_ERROR("  2. Or use a different port number");
            LOG_ERROR("  3. Or wait a few seconds for the port to be released");
        }
        
        // [Live555] 回收使用环境
        fEnv->reclaim();
        fEnv = NULL;
        delete fScheduler;
        fScheduler = NULL;
        return;
    }
    LOG_INFO("RTSP server socket created successfully on port %d", config.port);
    
    // ========== 自定义函数调用 ==========
    // [自定义] 初始化视频处理器（使用配置中的视频参数，而非硬编码）
    fVideoHandler = VideoStreamHandler::createNew((void*)fEnv, config.videoConfig);
    if (fVideoHandler == nullptr) {
        LOG_ERROR("Failed to create VideoStreamHandler");
        cleanup();
        return;
    }
    LOG_INFO("VideoStreamHandler instance created");
    
    // [自定义] 初始化视频处理器
    if (!fVideoHandler->initialize()) {
        LOG_ERROR("Failed to initialize VideoStreamHandler");
        delete fVideoHandler;
        fVideoHandler = nullptr;
        cleanup();
        return;
    }
    LOG_INFO("VideoStreamHandler initialized (codec: %d, resolution: %dx%d, fps: %d)",
             config.videoConfig.codecType, config.videoConfig.width, 
             config.videoConfig.height, config.videoConfig.frameRate);
    
    // ========== Live555库函数调用 ==========
    // [Live555] 创建服务器媒体会话（使用配置中的流名称和描述）
    fMediaSession = ServerMediaSession::createNew(*fEnv, config.streamName, "H.264 Stream", config.streamDescription);
    if (fMediaSession == nullptr) {
        LOG_ERROR("Failed to create media session");
        cleanup();
        return;
    }
    LOG_INFO("ServerMediaSession created for stream '%s'", config.streamName);
    
    // ========== 自定义函数调用 ==========
    fLiveSource = T32H264LiveSource::createNew(*fEnv);
    if (fLiveSource == nullptr) {
        LOG_ERROR("Failed to create T32H264LiveSource");
        cleanup();
        return;
    }
    LOG_INFO("T32H264LiveSource created");

    fVideoReplicator = StreamReplicator::createNew(*fEnv, fLiveSource, False);
    if (fVideoReplicator == nullptr) {
        LOG_ERROR("Failed to create StreamReplicator");
        Medium::close(fLiveSource);
        fLiveSource = nullptr;
        cleanup();
        return;
    }
    LOG_INFO("StreamReplicator created");

    fVideoSubsession = H264VideoServerMediaSubsession::createNew(*fEnv, fVideoReplicator, fVideoHandler, True);
    if (fVideoSubsession == nullptr) {
        LOG_ERROR("Failed to create H.264 video subsession");
        Medium::close(fVideoReplicator);
        fVideoReplicator = nullptr;
        Medium::close(fLiveSource);
        fLiveSource = nullptr;
        cleanup();
        return;
    }
    LOG_INFO("H.264 subsession created (stream name: %s)", config.streamName);
    
    // ========== Live555库函数调用 ==========
    // [Live555] 将视频子会话添加到媒体会话
    fMediaSession->addSubsession(fVideoSubsession);
    LOG_INFO("Video subsession attached to media session");
 
    // [Live555] 将媒体会话添加到RTSP服务器
    fRTSPServer->addServerMediaSession(fMediaSession);
    LOG_INFO("Media session registered with RTSP server");
    
    // [Live555] 获取RTSP流URL
    char* url = fRTSPServer->rtspURL(fMediaSession);
    if (url) {
        LOG_INFO("RTSP stream URL: %s", url);
        LOG_INFO("Clients can connect using: %s", url);
        delete[] url;
    } else {
        LOG_WARNING("Failed to get RTSP stream URL");
    }
    
    {
        // [自定义] 使用RAII锁保护
    ThreadSafeUtils::ScopedLock lock(fMutex);
        fServerRunning = true;
    }
    LOG_INFO("========================================");
    LOG_INFO("RTSP server initialized successfully!");
    LOG_INFO("Listening on port: %d", config.port);
    LOG_INFO("Waiting for client connections...");
    LOG_INFO("========================================");
    
    // 创建事件循环观察变量（Live555使用char*作为EventLoopWatchVariable）
    fEventLoopWatchVar = new EventLoopWatchVariable(0);
    
    // ========== Live555库函数调用 ==========
    // [Live555] 运行事件循环，直到收到停止信号
    fEnv->taskScheduler().doEventLoop(fEventLoopWatchVar);
    
    LOG_INFO("RTSP server thread exiting");
}

// 清理资源
void RTSPServerManager::cleanup() {
    // 参考 RTSP 项目的清理方式：先停止所有活动，然后才释放资源
    LOG_INFO("Commencing RTSP server cleanup");
    
    if (fVideoSubsession != nullptr) {
        try {
            Medium::close(fVideoSubsession);
        } catch (...) {
            LOG_WARNING("Exception while closing video subsession");
        }
        fVideoSubsession = nullptr;
    }

    if (fVideoReplicator != nullptr) {
        try {
            Medium::close(fVideoReplicator);
        } catch (...) {
            LOG_WARNING("Exception while closing StreamReplicator");
        }
        fVideoReplicator = nullptr;
    }

    if (fLiveSource != nullptr) {
        try {
            Medium::close(fLiveSource);
        } catch (...) {
            LOG_WARNING("Exception while closing live source");
        }
        fLiveSource = nullptr;
    }

    if (fMediaSession != nullptr) {
        try {
            Medium::close(fMediaSession);
        } catch (...) {
            LOG_WARNING("Exception while closing media session");
        }
        fMediaSession = nullptr;
    }

    if (fRTSPServer != nullptr) {
        try {
            LOG_INFO("Closing RTSP server to release port...");
            Medium::close(fRTSPServer);
            usleep(100000);
            LOG_INFO("RTSP server closed, port released");
        } catch (...) {
            LOG_WARNING("Exception while closing RTSP server");
        }
        fRTSPServer = nullptr;
    }

    if (fVideoHandler != nullptr) {
        delete fVideoHandler;
        fVideoHandler = nullptr;
    }

    // 音频功能暂未实现
    // if (fAudioHandler != nullptr) {
    //     delete fAudioHandler;
    //     fAudioHandler = nullptr;
    // }

    if (fEventLoopWatchVar != nullptr) {
        delete fEventLoopWatchVar;
        fEventLoopWatchVar = nullptr;
    }

    if (fScheduler != nullptr) {
        delete fScheduler;
        fScheduler = nullptr;
    }

    if (fEnv != nullptr) {
        try {
            fEnv->reclaim();
        } catch (...) {
            LOG_WARNING("Exception while reclaiming environment");
        }
        fEnv = nullptr;
    }

    LOG_INFO("RTSP server cleanup completed");

    return;
}

// ========== LoggingRTSPServer实现 ==========

LoggingRTSPServer* LoggingRTSPServer::createNew(UsageEnvironment& env, Port ourPort,
                                                UserAuthenticationDatabase* authDatabase,
                                                unsigned reclamationSeconds) {
    int ourSocketIPv4 = setUpOurSocket(env, ourPort, AF_INET);
    if (ourSocketIPv4 < 0) {
        return NULL;
    }
    
    int ourSocketIPv6 = -1;  // IPv6暂不支持
    return new LoggingRTSPServer(env, ourSocketIPv4, ourSocketIPv6, ourPort, authDatabase, reclamationSeconds);
}

LoggingRTSPServer::LoggingRTSPServer(UsageEnvironment& env,
                                     int ourSocketIPv4, int ourSocketIPv6, Port ourPort,
                                     UserAuthenticationDatabase* authDatabase,
                                     unsigned reclamationSeconds)
    : RTSPServer(env, ourSocketIPv4, ourSocketIPv6, ourPort, authDatabase, reclamationSeconds) {
}

LoggingRTSPServer::~LoggingRTSPServer() {
}

GenericMediaServer::ClientConnection* LoggingRTSPServer::createNewClientConnection(int clientSocket, struct sockaddr_storage const& clientAddr) {
    return new LoggingRTSPClientConnection(*this, clientSocket, clientAddr);
}

GenericMediaServer::ClientSession* LoggingRTSPServer::createNewClientSession(u_int32_t sessionId) {
    return new LoggingRTSPClientSession(*this, sessionId);
}

// ========== LoggingRTSPClientConnection实现 ==========

LoggingRTSPServer::LoggingRTSPClientConnection::LoggingRTSPClientConnection(LoggingRTSPServer& ourServer,
                                                                             int clientSocket, struct sockaddr_storage const& clientAddr,
                                                                             Boolean useTLS)
    : RTSPClientConnection(ourServer, clientSocket, clientAddr, useTLS) {
}

LoggingRTSPServer::LoggingRTSPClientConnection::~LoggingRTSPClientConnection() {
}

void LoggingRTSPServer::LoggingRTSPClientConnection::handleRequestBytes(int newBytesRead) {
    RTSPClientConnection::handleRequestBytes(newBytesRead);
}

void LoggingRTSPServer::LoggingRTSPClientConnection::handleCmd_OPTIONS() {
    logRequest("OPTIONS", "");
    RTSPClientConnection::handleCmd_OPTIONS();
}

void LoggingRTSPServer::LoggingRTSPClientConnection::handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {
    logRequest("DESCRIBE", fullRequestStr ? fullRequestStr : "");
    RTSPClientConnection::handleCmd_DESCRIBE(urlPreSuffix, urlSuffix, fullRequestStr);
}

void LoggingRTSPServer::LoggingRTSPClientConnection::handleCmd_bad() {
    logRequest("BAD", "");
    RTSPClientConnection::handleCmd_bad();
}

void LoggingRTSPServer::LoggingRTSPClientConnection::logClientInfo(const char* action) {
    char* ip = getClientIP();
    int port = getClientPort();
    LOG_INFO("[RTSP Client] %s - Client: %s:%d", action, ip ? ip : "unknown", port);
    delete[] ip;
}

void LoggingRTSPServer::LoggingRTSPClientConnection::logRequest(const char* method, const char* url) {
    char* ip = getClientIP();
    LOG_DEBUG("[RTSP Request] %s from %s: %s", method, ip ? ip : "unknown", url ? url : "");
    delete[] ip;
}

char* LoggingRTSPServer::LoggingRTSPClientConnection::getClientIP() const {
    char* ip = new char[INET6_ADDRSTRLEN];
    if (fClientAddr.ss_family == AF_INET) {
        struct sockaddr_in* addr4 = (struct sockaddr_in*)&fClientAddr;
        inet_ntop(AF_INET, &addr4->sin_addr, ip, INET6_ADDRSTRLEN);
    } else if (fClientAddr.ss_family == AF_INET6) {
        struct sockaddr_in6* addr6 = (struct sockaddr_in6*)&fClientAddr;
        inet_ntop(AF_INET6, &addr6->sin6_addr, ip, INET6_ADDRSTRLEN);
    } else {
        strcpy(ip, "unknown");
    }
    return ip;
}

int LoggingRTSPServer::LoggingRTSPClientConnection::getClientPort() const {
    if (fClientAddr.ss_family == AF_INET) {
        struct sockaddr_in* addr4 = (struct sockaddr_in*)&fClientAddr;
        return ntohs(addr4->sin_port);
    } else if (fClientAddr.ss_family == AF_INET6) {
        struct sockaddr_in6* addr6 = (struct sockaddr_in6*)&fClientAddr;
        return ntohs(addr6->sin6_port);
    }
    return 0;
}

// ========== LoggingRTSPClientSession实现 ==========

LoggingRTSPServer::LoggingRTSPClientSession::LoggingRTSPClientSession(LoggingRTSPServer& ourServer, u_int32_t sessionId)
    : RTSPClientSession(ourServer, sessionId) {
}

LoggingRTSPServer::LoggingRTSPClientSession::~LoggingRTSPClientSession() {
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_SETUP(RTSPClientConnection* ourClientConnection,
                                                                   char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {
    logSessionInfo("SETUP");
    RTSPClientSession::handleCmd_SETUP(ourClientConnection, urlPreSuffix, urlSuffix, fullRequestStr);
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_SETUP_afterLookup1(ServerMediaSession* sms) {
    RTSPClientSession::handleCmd_SETUP_afterLookup1(sms);
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_SETUP_afterLookup2(ServerMediaSession* sms) {
    RTSPClientSession::handleCmd_SETUP_afterLookup2(sms);
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_PLAY(RTSPClientConnection* ourClientConnection,
                                                                  ServerMediaSubsession* subsession, char const* fullRequestStr) {
    logSessionInfo("PLAY");
    RTSPClientSession::handleCmd_PLAY(ourClientConnection, subsession, fullRequestStr);
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_TEARDOWN(RTSPClientConnection* ourClientConnection,
                                                                     ServerMediaSubsession* subsession) {
    logSessionInfo("TEARDOWN");
    RTSPClientSession::handleCmd_TEARDOWN(ourClientConnection, subsession);
}

void LoggingRTSPServer::LoggingRTSPClientSession::handleCmd_PAUSE(RTSPClientConnection* ourClientConnection,
                                                                  ServerMediaSubsession* subsession) {
    logSessionInfo("PAUSE");
    RTSPClientSession::handleCmd_PAUSE(ourClientConnection, subsession);
}

void LoggingRTSPServer::LoggingRTSPClientSession::logSessionInfo(const char* action) {
    LOG_INFO("[RTSP Session] %s - Session ID: %u", action, fOurSessionId);
}

char* LoggingRTSPServer::LoggingRTSPClientSession::getClientIP(RTSPClientConnection* conn) const {
    if (conn == NULL) return NULL;
    return strdup("unknown");  // 简化实现
}

int LoggingRTSPServer::LoggingRTSPClientSession::getClientPort(RTSPClientConnection* conn) const {
    if (conn == NULL) return 0;
    return 0;  // 简化实现
}

// ConfigManager的所有方法已在头文件中内联实现，这里不需要重复定义
// ========== C接口实现（合并自live555_rtsp_server.cpp） ==========

// 全局RTSP服务器管理器实例
static std::unique_ptr<RTSPServerManager> g_serverManager = nullptr;
static std::mutex g_serverManagerMutex;

// 检查端口是否可用
static bool checkPortAvailable(int port) {
    int testSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (testSocket < 0) return false;
    int reuse = 1;
    setsockopt(testSocket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);
    bool available = (bind(testSocket, (struct sockaddr*)&addr, sizeof(addr)) == 0);
    close(testSocket);
    return available;
}

extern "C" {

bool rtsp_server_start(int port) {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    if (g_serverManager != nullptr && g_serverManager->isRunning()) {
        LOG_WARNING("RTSP server already running, stopping it first...");
        g_serverManager->stop();
        g_serverManager.reset();
    }
    const int maxRetries = 10;
    const int retryDelayMs = 2000;
    bool portAvailable = false;
    for (int retry = 0; retry < maxRetries; retry++) {
        portAvailable = checkPortAvailable(port);
        if (portAvailable) {
            if (retry > 0) {
                LOG_INFO("Port %d is now available, waiting additional 1 second...", port);
                usleep(1000000);
            }
            break;
        }
        if (retry < maxRetries - 1) {
            LOG_WARNING("Port %d is in use, waiting %d ms before retry (%d/%d)...", port, retryDelayMs, retry + 1, maxRetries);
            usleep(retryDelayMs * 1000);
        }
    }
    if (!portAvailable) {
        LOG_ERROR("Port %d is still in use after %d retries", port, maxRetries);
        return false;
    }
    g_serverManager = std::unique_ptr<RTSPServerManager>(RTSPServerManager::createNew());
    if (g_serverManager == nullptr) {
        LOG_ERROR("Failed to create RTSP server manager");
        return false;
    }
    if (!g_serverManager->initialize(port)) {
        LOG_ERROR("Failed to initialize RTSP server");
        g_serverManager.reset();
        return false;
    }
    if (!g_serverManager->start()) {
        LOG_ERROR("Failed to start RTSP server");
        g_serverManager.reset();
        return false;
    }
    LOG_INFO("RTSP server started on port %d", port);
    return true;
}

void rtsp_server_stop() {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    LOG_INFO("Stopping RTSP server");
    if (g_serverManager != nullptr) {
        g_serverManager->stop();
        g_serverManager.reset();
    }
    LOG_INFO("RTSP server stopped");
}

void rtsp_server_mainloop() {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    if (g_serverManager != nullptr && g_serverManager->isRunning()) {
        usleep(500000);
    }
}

VideoStreamHandler* get_video_handler() {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    if (g_serverManager != nullptr) {
        return g_serverManager->getVideoHandler();
    }
    return NULL;
}

void update_video_params(unsigned char* spsData, size_t spsSize, unsigned char* ppsData, size_t ppsSize) {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    if (g_serverManager != nullptr) {
        g_serverManager->updateVideoParams(spsData, spsSize, ppsData, ppsSize);
    }
}

void notify_new_frame_available() {
    std::lock_guard<std::mutex> lock(g_serverManagerMutex);
    if (g_serverManager != nullptr) {
        g_serverManager->notifyNewFrameAvailable();
    }
}
} // extern "C"












